package net.tngou.tnfs.action.manage;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import net.tngou.tnfs.pojo.Gallery;
import net.tngou.tnfs.pojo.Picture;
import net.tngou.tnfs.util.DigestMD;
import net.tngou.tnfs.util.HttpConfig;
import net.tngou.tnfs.util.ImgUtil;
import net.tngou.tnfs.util.PathFormat;
/**
 *  
* @Description: 图片抓取
 */
public class ExtAction extends IndexAction {

	
	
	
	
	@Override
	public void execute() throws ServletException, IOException {
		printFreemarker("manage/ext.ftl", root);
	}
	

	/**
	 *  
	* @Description: 举得图片
	 */
	public void get() {
		
	}
	
	/**
	 *  
	* @Description: 保存
	 */
	public void save() {
		
		String title=request.getParameter("title");
		String galleryclass=request.getParameter("galleryclass");			
		String[] srcs = request.getParameterValues("srcs");
		String path=request.getParameter("path");
		if(StringUtils.isEmpty(path))path=File.separator+"ext"+File.separator;
		if(!path.startsWith(File.separator))path=File.separator+path;
		if(!path.endsWith(File.separator))path=path+File.separator;
		HttpConfig httpConfig = HttpConfig.getInstance();
		String savePath =httpConfig.getTnfspath()+File.separator+"img"+path;
		String saveUrl = path;
		Set<String> set = new HashSet<String>(Arrays.asList(srcs));
		List<String> list = new ArrayList<String>();
		for (String src : set) {
			
			String save = ImgUtil.DownImg(src, savePath, saveUrl, null);
			if(save!=null)list.add(PathFormat.format(save));
				
		}
		
		int id =0;
		if(list.size()>0)
		{
			Gallery gallery = new Gallery();
			gallery.setGalleryclass(Integer.parseInt(galleryclass));
			gallery.setTitle(title);
			gallery.setImg(list.get(0));
			gallery.setSize(list.size());
			id=(int) gallery.save();
			
			if(id>0)
			{
				
				for (String src : list) {
					Picture picture = new Picture();
					picture.setGallery(id);
					picture.setSrc(src);
					picture.save();
				}
				
			}
		}
		
		printHtml(id+"");
		
		
		
		
		
	}
}
